<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-600 rounded-lg overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
              </div>
            <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">代拿员</span>
          </div>
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 面包屑 -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2 text-sm text-gray-500">
        <button class="hover:text-blue-600" @click="$router.push('/courier/orders')">我的订单</button>
        <span class="mx-2">/</span>
        <span class="text-gray-900">订单详情</span>
      </div>
    </div>

    <!-- 内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左：订单信息 -->
        <section class="lg:col-span-2 bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-start justify-between mb-6">
            <div>
              <h1 class="text-2xl font-bold text-gray-900 mb-1">{{ detail.title }}</h1>
              <div class="flex items-center gap-3 text-sm text-gray-500">
                <span>订单编号：{{ orderId }}</span>
                <span>创建时间：{{ detail.time }}</span>
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium" :class="statusPill(detail.status)">{{ statusLabel(detail.status) }}</span>
              </div>
            </div>
            <div class="text-right">
              <div class="text-gray-500 text-sm">订单金额</div>
              <div class="text-2xl font-bold text-gray-900">¥{{ detail.amount }}</div>
            </div>
          </div>

          <div class="space-y-8">
            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">下单者信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">姓名：</span><span class="text-gray-900">{{ detail.userName || '匿名用户' }}</span></div>
                <div><span class="text-gray-500">联系电话：</span><span class="text-gray-900">{{ detail.userPhone || '—' }}</span></div>
                <div class="md:col-span-2"><span class="text-gray-500">备注：</span><span class="text-gray-900">{{ detail.remark || '—' }}</span></div>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">取件信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">取件地点：</span><span class="text-gray-900">{{ detail.pickupLocation || '一期丰巢' }}</span></div>
                <div><span class="text-gray-500">取件码/单号：</span><span class="text-gray-900">{{ detail.pickupRef || '—' }}</span></div>
                <div><span class="text-gray-500">期望时间：</span><span class="text-gray-900">{{ detail.pickupTime || '尽快' }}</span></div>
              </div>
              <div class="mt-3">
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-1.5 text-xs font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50"
                  @click="openPickupMap"
                >
                  查看取件点地图（高德）
                </button>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">送达信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">送达地点：</span><span class="text-gray-900">{{ detail.dropoffLocation || '—' }}</span></div>
                <div class="md:col-span-2"><span class="text-gray-500">详细地址：</span><span class="text-gray-900">{{ detail.dropoffDetail || '—' }}</span></div>
              </div>
              <div class="mt-3">
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-1.5 text-xs font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50"
                  @click="openDropoffMap"
                >
                  查看送达点地图（高德）
                </button>
              </div>
            </div>
          </div>
        </section>

        <!-- 右：状态与操作（已取消的订单不展示进度） -->
        <aside v-if="detail.status !== '已取消'" class="bg-white rounded-lg shadow-sm p-6 h-fit">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">订单进度</h3>
          <ol class="relative border-l-2 border-gray-300 ml-4 text-sm">
            <li class="mb-6 ml-4" v-for="(step, idx) in steps" :key="idx">
              <div class="absolute w-3 h-3 rounded-full -left-1.5 border" :class="idx <= currentStep ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-300'"></div>
              <time class="text-gray-400">{{ step.time }}</time>
              <div class="text-gray-900 font-medium">{{ step.title }}</div>
              <div class="text-gray-500">{{ step.desc }}</div>
            </li>
          </ol>
          <div class="mt-6 flex flex-col gap-3">
            <button v-if="detail.status === '配送中'" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700" @click="confirmPickup">确认取件</button>
            <button v-else-if="detail.status === '已取件'" class="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700" @click="confirmDeliver">通知送达</button>
            <button class="px-4 py-2 border border-blue-600 text-blue-600 rounded hover:bg-blue-50" @click="$router.push('/courier/orders')">返回列表</button>
          </div>
        </aside>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'CourierOrderDetail',
  components: { HeaderActions },
  data() {
    return {
      orderId: this.$route.params.id,
      detail: { title: '代拿订单' },
      steps: [],
      currentStep: 1,
      accepted: false,
      // 状态常量定义
      STATUS: {
        PENDING: 1,
        ACCEPTED: 2,
        PICKED_UP: 3,
        DELIVERED: 4,
        COMPLETED: 5,
        CANCELLED: 6
      }
    }
  },
  methods: {
    openPickupMap() {
      const loc = (this.detail && this.detail.pickupLocation) || ''
      if (!loc) {
        alert('暂无取件地点信息')
        return
      }
      const keyword = `云浮市 广东药科大学 都杨镇文华路368号 ${loc}`
      const url = `https://www.amap.com/search?query=${encodeURIComponent(keyword)}`
      const win = window.open(url, '_blank')
      if (!win) {
        window.location.href = url
      }
    },
    openDropoffMap() {
      const loc = (this.detail && (this.detail.dropoffDetail || this.detail.dropoffLocation)) || ''
      if (!loc) {
        alert('暂无送达地点信息')
        return
      }
      const keyword = `云浮市 广东药科大学 都杨镇文华路368号 ${loc}`
      const url = `https://www.amap.com/search?query=${encodeURIComponent(keyword)}`
      const win = window.open(url, '_blank')
      if (!win) {
        window.location.href = url
      }
    },
    statusLabel(s) {
      const statusMap = {
        1: '待接单',
        2: '配送中',
        3: '已取件',
        4: '已送达',
        5: '已完成',
        6: '已取消'
      }
      return statusMap[s] || String(s || '待接单')
    },
    statusPill(s) {
      const pillMap = {
        1: 'bg-yellow-100 text-yellow-700',
        2: 'bg-blue-100 text-blue-700',
        3: 'bg-green-100 text-green-700',
        4: 'bg-purple-100 text-purple-700',
        5: 'bg-green-100 text-green-700',
        6: 'bg-red-100 text-red-700'
      }
      return pillMap[s] || 'bg-gray-100 text-gray-600'
    },
    async fetchDetail() {
        try {
          const { data } = await axios.get(`/api/orders/${this.orderId}`)
          const d = (data && data.data) || {}
          const status = Number(d.status) || 1
          const toText = (status) => {
            const statusMap = {
              1: '待接单',
              2: '配送中',
              3: '已取件',
              4: '已送达',
              5: '已完成',
              6: '已取消'
            }
            return statusMap[status] || '待接单'
          }
          const fmt = (t) => t ? String(t).replace('T',' ').slice(0,19) : '—'
          const fee = d.final_fee ?? d.suggested_fee ?? d.amount ?? d.fee ?? 0
        const delivery = d.delivery_address || ''
        // 尝试拆分送达地点与详细地址（以第一个空格分割）
        let dropLoc = delivery, dropDetail = ''
        if (delivery.includes(' ')) { const i = delivery.indexOf(' '); dropLoc = delivery.slice(0,i); dropDetail = delivery.slice(i+1) }

        this.detail = {
          title: '代拿订单',
          amount: Number(fee || 0).toFixed(2),
          time: fmt(d.created_at),
          status: toText(d.status),
          userName: d.order_user_nickname || '匿名用户',
          userPhone: d.order_user_phone || '—',
          remark: d.note || '—',
          pickupLocation: d.pickup_location || '—',
          pickupRef: d.pickup_code || '—',
          pickupTime: fmt(d.pickup_time) || '尽快',
          dropoffLocation: dropLoc || '—',
          dropoffDetail: dropDetail || '—'
        }
        this.accepted = status >= 2
        this.steps = [
          { title: '已下单', desc: '用户提交订单', time: fmt(d.created_at) },
          { title: '已接单', desc: '代拿员已接单', time: fmt(d.accepted_at) },
          { title: '已取件', desc: '已取件配送中', time: fmt(d.picked_up_at || d.accepted_at) },
          { title: '已送达', desc: '已通知用户取件', time: fmt(d.delivered_at || d.picked_up_at || d.accepted_at) },
          { title: '已完成', desc: '订单已完成', time: fmt(d.completed_at || d.updated_at) }
        ]
        this.currentStep = Math.min(status - 1, this.steps.length - 1)
      } catch (e) {
        console.error('获取订单详情失败', e)
        alert('获取订单详情失败')
      }
    },
    async acceptOrder() {
      const courierId = localStorage.getItem('userId')
      if (!courierId) { alert('请先登录'); this.$router.push('/login'); return }
      try {
        await axios.put(`/api/orders/${this.orderId}/accept`, { courier_user_id: Number(courierId) })
        await this.fetchDetail()
        alert('接单成功！请尽快前往取件。')
      } catch (e) {
        console.error('接单失败', e)
        alert('接单失败，请稍后再试')
      }
    },
    async confirmPickup() {
      try {
        await axios.post(`/api/orders/${this.orderId}/pickup`)
        await this.fetchDetail()
        alert('取件确认成功！')
      } catch (e) {
        console.error('确认取件失败', e)
        alert('确认取件失败，请稍后再试')
      }
    },
    async confirmDeliver() {
      try {
        await axios.post(`/api/orders/${this.orderId}/deliver`)
        await this.fetchDetail()
        alert('已通知用户取件！')
      } catch (e) {
        console.error('通知送达失败', e)
        alert('通知送达失败，请稍后再试')
      }
    }
  },
  mounted() {
    this.fetchDetail()
  }
}
</script>


